package com.competition.commgr.controller;

import com.competition.commgr.domain.Team;
import com.competition.commgr.mapper.TeamMapper;
import com.competition.commgr.service.ITeamService;
import com.competition.common.annotation.Log;
import com.competition.common.core.controller.BaseController;
import com.competition.common.core.domain.AjaxResult;
import com.competition.common.core.page.TableDataInfo;
import com.competition.common.enums.BusinessType;
import com.competition.common.utils.SecurityUtils;
import com.competition.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团队Controller
 */
@RestController
@RequestMapping("/commgr/team")
public class TeamController extends BaseController {
    @Autowired
    private ITeamService teamService;

    @Autowired
    private TeamMapper teamMapper;

    /**
     * 查询团队列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:list')")
    @GetMapping("/list")
    public TableDataInfo list(Team team) {
        startPage();
        List<Team> list = teamService.selectTeamList(team);
        return getDataTable(list);
    }

    /**
     * 导出团队列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:export')")
    @Log(title = "团队", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Team team) {
        List<Team> list = teamService.selectTeamList(team);
        ExcelUtil<Team> util = new ExcelUtil<Team>(Team.class);
        util.exportExcel(response, list, "团队数据");
    }

    /**
     * 获取团队详细信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping(value = "/{teamId}")
    public AjaxResult getInfo(@PathVariable("teamId") Long teamId) {
        return success(teamService.selectTeamByTeamId(teamId));
    }

    /**
     * 新增团队
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:add')")
    @Log(title = "团队", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Team team) {
        return toAjax(teamService.insertTeam(team));
    }

    /**
     * 修改团队
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "团队", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Team team) {
        return toAjax(teamService.updateTeam(team));
    }

    /**
     * 删除团队
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:remove')")
    @Log(title = "团队", businessType = BusinessType.DELETE)
    @DeleteMapping("/{teamIds}")
    public AjaxResult remove(@PathVariable Long[] teamIds) {
        return toAjax(teamService.deleteTeamByTeamIds(teamIds));
    }

    /**
     * 获取团队成员列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @GetMapping("/{teamId}/members")
    public AjaxResult getTeamMembers(@PathVariable("teamId") Long teamId) {
        List<Team.TeamMember> members = teamService.selectTeamMembers(teamId);
        return success(members);
    }

    /**
     * 添加团队成员
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "团队成员", businessType = BusinessType.INSERT)
    @PostMapping("/members")
    public AjaxResult addMember(@RequestBody Map<String, Object> map) {
        try {
            Long teamId = Long.valueOf(map.get("teamId").toString());
            Long userId = Long.valueOf(map.get("userId").toString());
            Long teamType = Long.valueOf(map.get("teamType").toString());
            return toAjax(teamService.insertTeamMember(teamId, userId, teamType));
        } catch (Exception e) {
            return error("添加成员失败: " + e.getMessage());
        }
    }

    /**
     * 修改团队成员信息（奖金、类型等）
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "团队成员", businessType = BusinessType.UPDATE)
    @PutMapping("/members")
    public AjaxResult updateMember(@RequestBody Map<String, Object> map) {
        try {
            // 直接传递整个map到Service层
            return toAjax(teamService.updateTeamMember(map));
        } catch (Exception e) {
            logger.error("修改成员信息失败", e);
            return error("修改成员信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除团队成员
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "团队成员", businessType = BusinessType.DELETE)
    @DeleteMapping("/members/{membersId}")
    public AjaxResult removeMember(@PathVariable Long membersId) {
        return toAjax(teamService.deleteTeamMember(membersId));
    }

    /**
     * 获取团队可分配奖金信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/distributableBonusInfo/{teamId}")
    public AjaxResult getDistributableBonusInfo(@PathVariable("teamId") Long teamId) {
        try {
            Map<String, Object> bonusInfo = teamService.selectDistributableBonusInfo(teamId);
            return success(bonusInfo);
        } catch (Exception e) {
            logger.error("获取团队可分配奖金信息失败", e);
            return error("获取团队可分配奖金信息失败: " + e.getMessage());
        }
    }

    /**
     * 执行奖金分配
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "奖金分配", businessType = BusinessType.UPDATE)
    @PostMapping("/distributeBonus/{teamId}")
    public AjaxResult distributeBonus(@PathVariable("teamId") Long teamId) {
        try {
            // 1. 获取可分配奖金信息
            Map<String, Object> bonusInfo = teamService.selectDistributableBonusInfo(teamId);

            String awardStatus = (String) bonusInfo.get("award_status");
            if ("未获奖".equals(awardStatus)) {
                return error("该团队尚未获奖，无法分配奖金");
            }

            // 2. 提取奖金金额
            Object instructorBonusObj = bonusInfo.get("instructor_bonus");
            Object participantBonusObj = bonusInfo.get("participant_bonus");

            // 处理类型转换
            Integer instructorBonus = convertToInteger(instructorBonusObj);
            Integer participantBonus = convertToInteger(participantBonusObj);

            // 3. 验证奖金金额
            if (instructorBonus == 0 && participantBonus == 0) {
                return error("奖金金额为零，无需分配");
            }

            String awardLevel = (String) bonusInfo.get("award_level");

            // 4. 通过Service层执行奖金分配
            Map<String, Object> distributionResult = teamService.executeBonusDistribution(
                    teamId, instructorBonus, participantBonus
            );

            Map<String, Object> result = new HashMap<>();
            result.put("message", "奖金分配成功");
            result.put("awardLevel", awardLevel);
            result.put("instructorBonus", instructorBonus);
            result.put("participantBonus", participantBonus);
            result.put("distributionResult", distributionResult);

            return success(result);

        } catch (Exception e) {
            logger.error("奖金分配失败", e);
            return error("奖金分配失败: " + e.getMessage());
        }
    }

    /**
     * 手动执行奖金分配（支持自定义金额）
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "手动奖金分配", businessType = BusinessType.UPDATE)
    @PostMapping("/manualDistributeBonus/{teamId}")
    public AjaxResult manualDistributeBonus(
            @PathVariable("teamId") Long teamId,
            @RequestBody Map<String, Object> params) {
        try {
            Integer instructorBonus = convertToInteger(params.get("instructorBonus"));
            Integer participantBonus = convertToInteger(params.get("participantBonus"));

            // 通过Service层执行奖金分配
            Map<String, Object> distributionResult = teamService.executeBonusDistribution(
                    teamId, instructorBonus, participantBonus
            );

            Map<String, Object> result = new HashMap<>();
            result.put("message", "手动奖金分配成功");
            result.put("instructorBonus", instructorBonus);
            result.put("participantBonus", participantBonus);
            result.put("distributionResult", distributionResult);

            return success(result);

        } catch (Exception e) {
            logger.error("手动奖金分配失败", e);
            return error("手动奖金分配失败: " + e.getMessage());
        }
    }

    /**
     * 查询分配后的奖金结果
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/distributionResult/{teamId}")
    public AjaxResult getDistributionResult(@PathVariable("teamId") Long teamId) {
        try {
            Map<String, Object> distributionResult = teamService.selectBonusDistributionResult(teamId);
            return success(distributionResult);
        } catch (Exception e) {
            logger.error("查询分配结果失败", e);
            return error("查询分配结果失败: " + e.getMessage());
        }
    }

    /**
     * 检查团队是否有获奖记录
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/checkAward/{teamId}")
    public AjaxResult checkTeamHasAward(@PathVariable("teamId") Long teamId) {
        try {
            boolean hasAward = teamService.checkTeamHasAward(teamId);
            Map<String, Object> result = new HashMap<>();
            result.put("teamId", teamId);
            result.put("hasAward", hasAward);
            return success(result);
        } catch (Exception e) {
            logger.error("检查获奖记录失败", e);
            return error("检查获奖记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用用户列表（用于添加团队成员）
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @GetMapping("/availableUsers")
    public AjaxResult getAvailableUsers() {
        List<Map<String, Object>> availableUsers = teamService.selectAvailableUsers();
        return success(availableUsers);
    }

    /**
     * 调试接口：获取用户团队详细信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/debugTeamsDetail")
    public AjaxResult debugTeamsDetail() {
        Long userId = getUserId();
        List<Map<String, Object>> debugInfo = teamService.debugUserTeamsDetail(userId);
        return success(debugInfo);
    }

    /**
     * 检查所有团队信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/checkAllTeams")
    public AjaxResult checkAllTeams() {
        Long userId = getUserId();
        Map<String, Object> checkResult = teamService.checkAllUserTeams(userId);
        return success(checkResult);
    }

    /**
     * 类型转换工具方法
     */
    private Integer convertToInteger(Object obj) {
        if (obj == null) {
            return 0;
        }
        if (obj instanceof Long) {
            return ((Long) obj).intValue();
        } else if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof BigDecimal) {
            return ((BigDecimal) obj).intValue();
        } else if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                return 0;
            }
        }
        return 0;
    }


    /**
     * 重置团队奖金
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "重置团队奖金", businessType = BusinessType.UPDATE)
    @PostMapping("/resetBonus/{teamId}")
    public AjaxResult resetTeamBonus(@PathVariable("teamId") Long teamId) {
        try {
            Map<String, Object> result = teamService.resetTeamBonus(teamId);
            return success(result);
        } catch (Exception e) {
            logger.error("重置团队奖金失败", e);
            return error("重置团队奖金失败: " + e.getMessage());
        }
    }

    /**
     * 重置成员奖金
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:edit')")
    @Log(title = "重置成员奖金", businessType = BusinessType.UPDATE)
    @PostMapping("/resetMemberBonus/{membersId}")
    public AjaxResult resetMemberBonus(@PathVariable("membersId") Long membersId) {
        try {
            Map<String, Object> result = teamService.resetMemberBonus(membersId);
            return success(result);
        } catch (Exception e) {
            logger.error("重置成员奖金失败", e);
            return error("重置成员奖金失败: " + e.getMessage());
        }
    }


    /**
     * 检查团队管理权限
     */
    @PreAuthorize("@ss.hasPermi('commgr:team:query')")
    @GetMapping("/checkPermission/{teamId}")
    public AjaxResult checkTeamPermission(@PathVariable("teamId") Long teamId) {
        try {
            boolean hasPermission = teamService.checkTeamManagementPermission(teamId);
            Map<String, Object> firstInstructorInfo = teamService.getFirstInstructorInfo(teamId);

            Map<String, Object> result = new HashMap<>();
            result.put("hasPermission", hasPermission);
            result.put("firstInstructorInfo", firstInstructorInfo);
            result.put("currentUserId", SecurityUtils.getUserId());

            return success(result);
        } catch (Exception e) {
            logger.error("检查团队权限失败", e);
            return error("检查团队权限失败");
        }
    }
}